package com.csu.device.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.csu.device.dao.BehaviorDao;
import com.csu.device.dao.DeviveDao;
import com.csu.device.entity.Behavior;
import com.csu.device.entity.DeviceBinding;
import com.csu.device.entity.DeviceRela;
import com.csu.device.service.DeviveBindingService;
import com.csu.device.service.HardWareService;
import com.csu.util.PageUtils;
import com.csu.util.Query;
import com.csu.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeviveBindingServiceImpl implements DeviveBindingService {

    @Autowired
    private DeviveDao deviveDao;

    @Autowired
    private HardWareService hardWareService;

    @Autowired
    private BehaviorDao behaviorDao;

    @Autowired
    private DeviveBindingService deviveBindingService;


    @Override
    public PageUtils findDeviceBinding(Map<String, Object> map) {
        //查询列表数据
        List<Map<String, Object>> deviceExampleList = deviveDao.findDeviceBinding(map);
        Map<String, Object> param;
        for (Map d : deviceExampleList) {
            //遍历查询绑定的设备
            param = new HashMap<>();
            param.put("id", d.get("id"));
            d.put("binding", deviveDao.findRela(param));
        }

        int total = deviveDao.findDeviceBindingCount(map);
        PageUtils pageUtils = new PageUtils(deviceExampleList, total);
        return pageUtils;
    }

    @Override
    public Integer findDeviceBindingCount(Map<String, Object> map) {
        return deviveDao.findDeviceBindingCount(map);
    }

    @Override
    public Integer addDevive(DeviceBinding deviceBinding) {
        int id = 0;
        deviceBinding.setCreateBy("1");
        deviceBinding.setUpdateBy("1");
        deviceBinding.setDeviceSn(deviceBinding.getDeviceSn().trim());
        id = deviveDao.addDeviceBinding(deviceBinding);
        if (id > 0) {
            List<DeviceRela> binding = deviceBinding.getBinding();
            for (DeviceRela deviceBindingRelaDO : binding) {
                if (null == deviceBindingRelaDO.getBindingType() || "".equals(deviceBindingRelaDO.getName())) {
                    continue;
                }
                deviceBindingRelaDO.setDevcieExampleId(deviceBinding.getId());
                deviveDao.addDeviceRela(deviceBindingRelaDO);
            }
        }
        //刷新redis 缓存
        Map<String, String> map = new HashMap<>();
        map.put("id", deviceBinding.getId() + "");
        hardWareService.initDeviceData(map);

        return id;
    }

    @Override
    public Integer updateDevive(DeviceBinding deviceBinding) {

        if (deviceBinding.getDeviceState() != 0) {
            //刷新redis
            String sn = deviveDao.getSn(deviceBinding);
            RedisUtil.del(sn);
        }

        return deviveDao.updateDeviceBinding(deviceBinding);
    }

    @Override
    public Integer deleteDevice(DeviceBinding deviceBinding) {
        int res = 0;
        String sn = deviveDao.getSn(deviceBinding);
        deviceBinding.setDeviceSn(sn);
        if (deviveDao.deleteDeviceBinding(deviceBinding) > 0) {
            if (deviveDao.deleteDeviceRela(deviceBinding) > 0) {
                res = 1;
            }
        }
        RedisUtil.del(sn);
        return res;
    }

    @Override
    public List<Map<String, Object>> findAllBehaviorToView(Map<String, Object> map) {
        return behaviorDao.findAllBehaviorToView(map);
    }


    /**
     * 报警历史数据接口
     *
     * @param map
     * @return
     */
    @Override
    public List<Behavior> findAllBehaviorByError(Map<String, Object> map) {
        return behaviorDao.findAllBehaviorByError(map);
    }

    @Override
    public Integer bandCard(String userId, String deviceSn, String userName) {

        //如果redis硬件设备编号重复就删除
        if(RedisUtil.hasKey(deviceSn)){
            return 0;
        }

        DeviceBinding deviceBinding = new DeviceBinding();
        deviceBinding.setDeviceSn(deviceSn);
        deviceBinding.setDeviceType(15);
        deviceBinding.setDeviceState(0);
        DeviceRela rela = new DeviceRela();
        rela.setBindingType(1);
        rela.setName(userName);
        rela.setDeviceBindingId(userId);
        List<DeviceRela> binding = new ArrayList<>();
        binding.add(rela);
        deviceBinding.setBinding(binding);

        Map<String,Object> map= new HashMap();
        map.put("deviceSn",deviceSn);
        PageUtils pageUtils= deviveBindingService.findDeviceBinding(map);
        if(pageUtils.getRows().size()!=0){
               return 0;
        }else{
            return this.addDevive(deviceBinding);
        }
    }

    @Override
    public Integer unBandCard(String deviceSn) {
        DeviceBinding deviceBinding = new DeviceBinding();
        deviceBinding.setDeviceSn(deviceSn);
        deviceBinding.setId(deviveDao.getId(deviceBinding));
        return this.deleteDevice(deviceBinding);
    }

    @Override
    public List<Map<String, Object>> findAllBehaviorByScene(Map<String, Object> map) {
        return behaviorDao.findAllBehaviorByScene(map);
    }

    @Override
    public PageUtils findAllBehaviorByPage(Map<String, Object> map) {
        //查询列表数据
        Query query = new Query(map);
        List<Map<String, Object>> mapList = behaviorDao.findAllBehaviorByPage(query);
        int total = behaviorDao.findAllBehaviorByPageCount(map);
        PageUtils pageUtils = new PageUtils(mapList, total);
        return pageUtils;
    }

    @Override
    public int updateBehaviorByMessage(Map<String, Object> map) {
        return behaviorDao.updateBehaviorByMessage(map);
    }

    @Override
    public List<Map<String, Object>> findDeviceSnByUserIdOrTypeId(Map<String, Object> map) {
        return behaviorDao.findDeviceSnByUserIdOrTypeId(map);
    }

    @Override
    public List<String> allUserId() {
        return deviveDao.allUserId();
    }

    @Override
    public JSONArray findAllDevice(Map<String, Object> map) {

        List<Map<String, Object>> list = deviveDao.findAllDevice(map);
        Map<String, JSONObject> hasMap = new HashMap<>();
        JSONArray ck;
        JSONObject jsonObject;
        for (Map data : list) {
            if (hasMap.containsKey(data.get("equipment_id"))) {
                jsonObject = hasMap.get(data.get("equipment_id"));
                ck = jsonObject.getJSONArray("data");
            } else {
                jsonObject = new JSONObject();
                jsonObject.put("name", data.get("name") + ":" + data.get("position_name"));
                ck = new JSONArray();
            }
            ck.add(JSONObject.parseObject(data.get("data_value").toString()));
            jsonObject.put("data", ck);
            hasMap.put(data.get("equipment_id").toString(), jsonObject);
        }

        JSONArray res = new JSONArray();
        for (JSONObject s : hasMap.values()) {
            res.add(s);
        }
        return res;
    }

    @Override
    public Integer addDeviceRela(DeviceRela deviceRela) {
        return null;
    }

    @Override
    public Integer deleteByDeviceRela(DeviceRela deviceRela) {
        return null;
    }

    @Override
    public JSONArray findBtype() {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        List<Map<String, Object>> list = deviveDao.findBtype();
        for (Map map : list) {
            jsonObject=new JSONObject();
            jsonObject.put("value",map.get("num"));
            if ("0".equals(map.get("behavior_type").toString())) {
                jsonObject.put("name","体征监测");
            }
            if ("1".equals(map.get("behavior_type").toString())) {
                jsonObject.put("name","环境监测");
            }
            if ("2".equals(map.get("behavior_type").toString())) {
                jsonObject.put("name","GPS监测");
            }
            if ("3".equals(map.get("behavior_type").toString())) {
                jsonObject.put("name","睡眠监测");
            }
            if ("5".equals(map.get("behavior_type").toString())) {
                jsonObject.put("name","一键呼救");
            }
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }
}
